<?php

namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\model\Group as GroupModel;

class Group extends Admin
{
    protected $hisiModel = 'Group';//模型名称[通用添加、修改专用]
    protected $hisiValidate = 'Group';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize()
    {
        parent::initialize();
        $factoryKV =db('factory')->where([['status','=',1],['type','=',0]])->order("order desc, id desc")->column('name', 'id');
        $this->assign('factoryKV', $factoryKV);
    }

    public function index()
    {
        $factoryKV =db('factory')->where([['status','=',1],['type','=',0]])->order("order desc, id desc")->column('name', 'id');
        if ($this->request->isAjax()) {
            $where = $data = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $keyword = $this->request->param('keyword/s');
            $factorId      = $this->request->param('factory_id/d', 0);
            $where[] = ['g.status', 'eq', 1];
            $where[] = ['f.type','=',0];
            if ($keyword) {
                $where[] = ['g.name', 'like', "%{$keyword}%"];
            }
            if ($factorId) {
                $where[] = ['factory_id', '=', $factorId];
            }
            $order = 'g.order desc, g.id desc';
            $list = GroupModel::alias('g')
                ->field('g.*,f.name as factory_name')
                ->where($where)
                ->join('factory f', 'f.id=g.factory_id')
                ->page($page)
                ->limit($limit)
                ->order($order)
                ->select();
            $data['count'] = GroupModel::alias('g') ->join('factory f', 'f.id=g.factory_id')->where($where)->count();
            $list = empty($list) ? [] : $list->toArray();
            $data['data'] = $list;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $assign = [
            'factoryKV' => [0 => '请选择'] + $factoryKV,
        ];
        return $this->assign($assign)->fetch();
    }

}